package jnpf.permission.service.impl;


import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.dynamic.datasource.ds.GroupDataSource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.DataFieldType;
import jnpf.base.SearchMethodEnum;
import jnpf.base.UserInfo;
import jnpf.config.ConfigValueUtil;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.model.button.ButtonModel;
import jnpf.base.model.column.ColumnModel;
import jnpf.base.model.form.ModuleFormModel;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.model.resource.ResourceModel;
import jnpf.base.service.SystemService;
import jnpf.database.model.dto.PrepareSqlDTO;
import jnpf.database.sql.util.SqlFrameFastUtil;
import jnpf.database.util.ConnUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.DbTypeUtil;
import jnpf.database.util.JdbcUtil;
import jnpf.permission.constant.AuthorizeConst;
import jnpf.permission.entity.AuthorizeEntity;
import jnpf.permission.entity.OrganizeAdministratorEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.mapper.AuthorizeMapper;
import jnpf.permission.model.authorize.*;
import jnpf.permission.service.*;
import jnpf.util.*;
import jnpf.util.data.DataSourceContextHolder;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 操作权限
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Slf4j
@Service
@DSTransactional
public class AuthorizeServiceImpl extends ServiceImpl<AuthorizeMapper, AuthorizeEntity> implements AuthorizeService {

	@Autowired
	private UserRelationService userRelationService;
	@Autowired
	private DataSourceUtil dataSourceUtils;
	@Autowired
	private UserProvider userProvider;
	@Autowired
	private CacheKeyUtil cacheKeyUtil;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private OrganizeService organizeService;
	@Autowired
	private OrganizeAdministratorService organizeAdminIsTratorService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ConfigValueUtil configValueUtil;
	@Autowired
	private DataSource dataSource;

	@Override
	public AuthorizeVO getAuthorize(boolean isCache) {
		// 是否从缓冲里面获取权限
		if (isCache) {
			return getCacheAuthor(userProvider.get());
		} else {
			return getAuthorize(userProvider.get());
		}
	}

	private AuthorizeVO getCacheAuthor(UserInfo userInfo) {
		// 是否从缓冲里面获取权限
		String cacheKey = cacheKeyUtil.getUserAuthorize() + userInfo.getUserId();
		if (!redisUtil.exists(cacheKey)) {
			AuthorizeVO authorizeModel = getAuthorize(userInfo);
			if (authorizeModel.getModuleList().size() != 0) {
				redisUtil.insert(cacheKey, authorizeModel, 60);
			}
			return authorizeModel;
		} else {
			return JsonUtil.getJsonToBean(redisUtil.getString(cacheKey).toString(), AuthorizeVO.class);
		}
	}


	@Override
	public AuthorizeVO getAuthorize(UserInfo userInfo) {
		List<ModuleModel> moduleList = new ArrayList<>();
		List<ButtonModel> buttonList = new ArrayList<>();
		List<ColumnModel> columnList = new ArrayList<>();
		List<ResourceModel> resourceList = new ArrayList<>();
		List<ModuleFormModel> formsList = new ArrayList<>();
		List<SystemBaeModel> systemList = new ArrayList<>();
		Boolean isAdmin = userInfo.getIsAdministrator();
//        String majorOrgId = userService.getInfo(userInfo.getUserId()).getOrganizeId();
		if (!isAdmin) {
			List<String> roleIds = new ArrayList<>();
			roleService.getRoleIdsByCurrentUser(userInfo.getOrganizeId()).forEach(role -> {
				//判断角色状态是否为有效，显示当前组织内角色的并集
				if (role != null) {
					roleIds.add("'" + role + "'" );
				}
			});
			if (roleIds.size() != 0) {
				String roleIdsStr = String.join("," , roleIds);
				systemList = this.baseMapper.findSystem(roleIdsStr);
				moduleList = this.baseMapper.findModule(roleIdsStr);
				buttonList = this.baseMapper.findButton(roleIdsStr);
				columnList = this.baseMapper.findColumn(roleIdsStr);
				resourceList = this.baseMapper.findResource(roleIdsStr);
				formsList = this.baseMapper.findForms(roleIdsStr);
			}

		} else {
			moduleList = this.baseMapper.findModuleAdmin(1);
			buttonList = this.baseMapper.findButtonAdmin(1);
			columnList = this.baseMapper.findColumnAdmin(1);
			resourceList = this.baseMapper.findResourceAdmin(1);
			formsList = this.baseMapper.findFormsAdmin(1);
			systemList = JsonUtil.getJsonToList(systemService.getList(null, true), SystemBaeModel.class);
		}
		return new AuthorizeVO(moduleList, buttonList, columnList, resourceList, formsList, systemList);
	}

	@Override
	public void save(String objectId, AuthorizeDataUpForm authorizeList) {
		SaveBatchForm form = JsonUtil.getJsonToBean(authorizeList, SaveBatchForm.class);
		form.setRoleIds(new String[]{objectId});
		this.saveBatch(form, false);
	}

	@Override
	public void saveBatch(SaveBatchForm saveBatchForm, boolean isBatch) {
		try {
			UserInfo userInfo = userProvider.get();
			String dbName = dataSourceUtils.getDbName();
			if (!"PostgreSQL".equals(dataSourceUtils.getDbType())) {
				dbName = userInfo.getTenantDbConnectionString() == null ?
						dataSourceUtils.getDbName() : userInfo.getTenantDbConnectionString();
			}

			List<AuthorizeEntity> objectList = new ArrayList<>();
			List<AuthorizeEntity> authorizeList = new ArrayList<>();
			// 设置权限归属对象
			setEntity(saveBatchForm.getUserIds(), AuthorizeConst.USER, objectList, true);
			setEntity(saveBatchForm.getPositionIds(), AuthorizeConst.POSITION, objectList, true);
			setEntity(saveBatchForm.getRoleIds(), AuthorizeConst.ROLE, objectList, true);
//            setEntity(saveBatchForm.getSystemIds(), AuthorizeConst.SYSTEM, objectList, true);
			// 设置权限模块
			setEntity(saveBatchForm.getButton(), AuthorizeConst.BUTTON, authorizeList, false);
			setEntity(saveBatchForm.getModule(), AuthorizeConst.MODULE, authorizeList, false);
			setEntity(saveBatchForm.getColumn(), AuthorizeConst.COLUMN, authorizeList, false);
			setEntity(saveBatchForm.getResource(), AuthorizeConst.RESOURCE, authorizeList, false);
			setEntity(saveBatchForm.getForm(), AuthorizeConst.FROM, authorizeList, false);
			setEntity(saveBatchForm.getSystemIds(), AuthorizeConst.SYSTEM, authorizeList, false);

			@Cleanup Connection conn = null;
			if (StringUtil.isNotEmpty(userInfo.getTenantId()) && "true".equals(userInfo.getTenantDbConnectionString())) {
				DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
				if (dynamicRoutingDataSource.getGroupDataSources().containsKey(DataSourceContextHolder.getDatasourceId() + "-master")) {
					GroupDataSource groupDataSource = dynamicRoutingDataSource.getGroupDataSources().get(DataSourceContextHolder.getDatasourceId() + "-master");
					if (groupDataSource.getDataSourceMap().size() > 0) {
						String key = "";
						for (String string : groupDataSource.getDataSourceMap().keySet()) {
							key = string;
							break;
						}
						DruidDataSource dataSource = (DruidDataSource) groupDataSource.getDataSourceMap().get(key);
						conn = ConnUtil.getConn(dataSource.getUsername(), dataSource.getPassword(), dataSource.getUrl());
					}
				}
			} else {
				conn = ConnUtil.getConn(dataSourceUtils, dbName);
			}
			// 删除角色相关信息
			List<String> objectIdAll = objectList.stream().map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
			userService.delCurRoleUser(objectIdAll);
			if (!isBatch) {
				String ids = String.join("," , objectIdAll);
				JdbcUtil.creUpDe(new PrepareSqlDTO(conn, XSSEscape.escapeEmpty(SqlFrameFastUtil.AUTHOR_DEL.replace("{authorizeIds}" , ids))));
			}

			// 插入数据
			String sql = DbTypeUtil.checkOracle(dataSourceUtils) || DbTypeUtil.checkPostgre(dataSourceUtils) ?
					SqlFrameFastUtil.INSERT_AUTHORIZE2 : SqlFrameFastUtil.INSERT_AUTHORIZE;
			if (configValueUtil.isMultiTenancy() && "PostgreSQL".equals(dataSourceUtils.getDbType())) {
				if (!"true".equals(userInfo.getTenantDbConnectionString())) {
					String tenantDbConnectionString = userInfo.getTenantDbConnectionString();
					tenantDbConnectionString = StringUtil.isNotEmpty(tenantDbConnectionString) ? tenantDbConnectionString + "." : "";
					sql = "INSERT INTO " + tenantDbConnectionString + "base_authorize (F_ID, F_ITEMTYPE, F_ITEMID, F_OBJECTTYPE, F_OBJECTID, F_SORTCODE, F_CREATORTIME, F_CREATORUSERID ) VALUES  (?,?,?,?,?,?,TO_DATE(?,'yyyy-mm-dd hh24:mi:ss'),?)";
				}
			}
			PrepareSqlDTO dto = new PrepareSqlDTO(conn, sql);
			for (int i = 0; i < objectList.size(); i++) {
				for (AuthorizeEntity entityItem : authorizeList) {
					dto.addMultiData(
							RandomUtil.uuId(),
							entityItem.getItemType(),
							entityItem.getItemId(),
							objectList.get(i).getObjectType(),
							objectList.get(i).getObjectId(),
							i,
							DateUtil.getNow(),
							userInfo.getUserId()
					);
				}
			}
			int[] i = JdbcUtil.creUpDeBatchOneSql(dto);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("权限报错:" + e.getMessage());
		}
	}

	/**
	 * 权限
	 */
	private void setEntity(String[] ids, String type, List<AuthorizeEntity> entityList, Boolean objectFlag) {
		if (ids != null) {
			for (String id : ids) {
				AuthorizeEntity entity = new AuthorizeEntity();
				if (objectFlag) {
					entity.setObjectType(type);
					entity.setObjectId(id);
				} else {
					entity.setItemType(type);
					entity.setItemId(id);
				}
				entityList.add(entity);
			}
		}
	}

	@Override
	public List<AuthorizeEntity> getListByUserId(boolean isAdmin, String userId) {
		if (!isAdmin) {
			QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().in(UserRelationEntity::getUserId, userId);
			List<UserRelationEntity> list = userRelationService.list(queryWrapper);
			List<String> userRelationList = list.stream().map(u -> u.getObjectId()).collect(Collectors.toList());
			userRelationList.add(userId);
			QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
			wrapper.lambda().in(AuthorizeEntity::getObjectId, userRelationList);
			return this.list(wrapper);
		} else {
			return new ArrayList<>();
		}
	}

	@Override
	public List<AuthorizeEntity> getListByObjectId(String objectId) {
		QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
		return this.list(queryWrapper);
	}

	@Override
	public Boolean existByObjId(String objectId) {
		QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
		queryWrapper.lambda().eq(AuthorizeEntity::getItemType, "module" );
		return this.count(queryWrapper) > 0;
	}

	@Override
	public List<SystemBaeModel> systemListByRoleIds(List<String> roleIds) {
		StringJoiner joiner = new StringJoiner("," );
		roleIds.forEach(t -> joiner.add("'" + t + "'" ));
		List<SystemBaeModel> systemBaeModelList = this.baseMapper.findSystem(joiner.toString());
		return systemBaeModelList == null ? new ArrayList<>(16) : systemBaeModelList;
	}

	@Override
	public List<AuthorizeEntity> getListByObjectId(String objectId, String itemType) {
		QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
		queryWrapper.lambda().eq(AuthorizeEntity::getItemType, itemType);
		return this.list(queryWrapper);
	}

	@Override
	public List<AuthorizeEntity> getListByObjectAndItem(String itemId, String objectType) {
		QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(AuthorizeEntity::getObjectType, objectType).eq(AuthorizeEntity::getItemId, itemId);
		return this.list(queryWrapper);
	}

	@Override
	public List<AuthorizeEntity> getListByItemId(String itemId) {
		QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(AuthorizeEntity::getItemId, itemId);
		return this.list(queryWrapper);
	}

	@Override
	public void saveAuth(String itemId, SaveAuthForm saveAuthForm) {
		String creatorUserId = userProvider.get().getUserId();
		if (DbTypeUtil.checkOracle(dataSourceUtils)) {
			List<AuthorizeEntity> list = new ArrayList<>();
			for (int i = 0; i < saveAuthForm.getObjectId().length; i++) {
				AuthorizeEntity authorizeEntity = new AuthorizeEntity();
				authorizeEntity.setId(RandomUtil.uuId());
				authorizeEntity.setItemType("portal" );
				authorizeEntity.setItemId(itemId);
				authorizeEntity.setObjectType(saveAuthForm.getObjectType());
				authorizeEntity.setObjectId(saveAuthForm.getObjectId()[i]);
				authorizeEntity.setSortCode(Long.valueOf(i));
				authorizeEntity.setCreatorTime(new Date());
				authorizeEntity.setCreatorUserId(creatorUserId);
				list.add(authorizeEntity);
			}
			QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(AuthorizeEntity::getItemId, itemId);
			this.remove(queryWrapper);
			if (list.size() > 0) {
				for (AuthorizeEntity entity : list) {
					this.baseMapper.savaAuth(entity);
				}
			}
		} else {
			StringBuilder values = new StringBuilder();
			for (int i = 0; i < saveAuthForm.getObjectId().length; i++) {
				values.append("('" + RandomUtil.uuId() + "', " );
				values.append("'portal', " );
				values.append("'" + itemId + "', " );
				values.append("'" + saveAuthForm.getObjectType() + "', " );
				values.append("'" + saveAuthForm.getObjectId()[i] + "', " );
				values.append("'" + i + "', " );
				values.append("'" + DateUtil.getNow() + "', " );
				values.append("'" + creatorUserId + "')," );
			}
			QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(AuthorizeEntity::getItemId, itemId);
			this.remove(queryWrapper);
			if (!StringUtil.isEmpty(values.toString())) {
				values.deleteCharAt(values.length() - 1);
				this.baseMapper.saveBatch(values.toString());
			}
		}
	}

	/**
	 * 获取条件过滤
	 *
	 * @param conditionModel 数据权限条件模型
	 * @return
	 */
	@Override
	public QueryWrapper<T> getCondition(AuthorizeConditionModel conditionModel) {
		Object obj = conditionModel.getObj();
		String moduleId = conditionModel.getModuleId();
		String tableName = conditionModel.getTableName();
		UserInfo userInfo = userProvider.get();
		QueryWrapper<T> queryWhere = (QueryWrapper<T>) obj;
		AuthorizeVO model = this.getAuthorize(true);
		List<ResourceModel> resourceList = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
		if (resourceList.size() == 0) {
			return null;
		}
		List<ResourceModel> resourceList1 = new ArrayList<>();
		//拼接计数
		int t = 1;
		for (ResourceModel item : resourceList) {
			if (item.getAllData() != null && item.getAllData() == 1) {
				t = 0;
				break;
			}
			List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
			for (int i = 0; i < conditionModelList.size(); i++) {
				ConditionModel conditionItem = conditionModelList.get(i);
				for (int k = 0; k < conditionItem.getGroups().size(); k++) {
					ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
					String itemTable = fieldItem.getBindTable();
					if (StringUtil.isNotEmpty(itemTable) && itemTable.equalsIgnoreCase(tableName)) {
						resourceList1.add(item);
					}
				}
			}
		}
		if (t == 1) {
			if (resourceList1.size() > 0) {
				queryWhere.and(tw -> {
					for (ResourceModel item : resourceList1) {
						List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
						for (int i = 0; i < conditionModelList.size(); i++) {
							ConditionModel conditionItem = conditionModelList.get(i);
							for (int k = 0; k < conditionItem.getGroups().size(); k++) {
								ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
								String itemField = fieldItem.getField();
								String itemValue = fieldItem.getValue();
								String itemMethod = fieldItem.getOp();
								Object value;
								if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) { //当前用户
									value = userInfo.getUserId();
									//任意文本 当前用户 当前组织 包含为模糊查询
									if (itemMethod.equals(SearchMethodEnum.Included.getMessage())){
										itemMethod = SearchMethodEnum.Like.getMessage();
									}
									if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
										itemMethod = SearchMethodEnum.NotLike.getMessage();
									}
								} else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) { //当前组织
									String orgId = userInfo.getOrganizeId();
									if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
										orgId = userInfo.getDepartmentId();
									}
									if (itemMethod.equals(SearchMethodEnum.Included.getMessage())){
										itemMethod = SearchMethodEnum.Like.getMessage();
									}
									if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
										itemMethod = SearchMethodEnum.NotLike.getMessage();
									}
									value = orgId;
								} else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) { //组织及子组织
									String orgId = userInfo.getOrganizeId();
									if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
										orgId = userInfo.getDepartmentId();
									}
									List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
									underOrganizations.add(orgId);
									value = underOrganizations;
								} else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) { //用户及用户下属
									List<String> idsList = new ArrayList<>();
									if (userInfo.getSubordinateIds().size() > 0) {
										idsList = userInfo.getSubordinateIds();
									}
									idsList.add(userInfo.getUserId());
									value =idsList;
								} else if (AuthorizeConditionEnum.BRANCHMANAGEORG.getCondition().equals(itemValue)) { //分管组织
									List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());
									//子
									List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);
									//父
									List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);
									List<String> allIdList = new ArrayList<>();
									//子
									List<String> childList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
									//父
									List<String> fathetList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
									for (String org : childList) {
										List<String> underOrganizations = organizeService.getUnderOrganizations(org);
										if (underOrganizations.size() > 0) {
											allIdList.addAll(underOrganizations);
										}
									}
									if (fathetList.size() > 0) {
										allIdList.addAll(fathetList);
									}
									//空集合处理
									if (allIdList.size() == 0) {
										allIdList.add("jnpfNullList" );
									}
									value = allIdList;
								} else if (AuthorizeConditionEnum.BRANCHMANAGEORGANIZEUNDER.getCondition().equals(itemValue)) { //分管组织及子组织
									List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());

									List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);

									List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

									List<String> allIdList = new ArrayList<>();
									//需要子集
									List<String> childList = new ArrayList<>();

									List<String> thisList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1)
											.map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

									List<String> subList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1)
											.map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

									if (thisList.size() > 0) {
										allIdList.addAll(thisList);
										childList.addAll(thisList);
									}
									if (subList.size() > 0) {
										childList.addAll(subList);
									}

									for (String orgID : childList) {
										List<String> underOrganizations = organizeService.getUnderOrganizations(orgID);
										if (underOrganizations.size() > 0) {
											allIdList.addAll(underOrganizations);
										}
									}
									if (allIdList.size() == 0) {
										allIdList.add("jnpfNullList" );
									}
									value = allIdList;
								} else {//任意文本
									value = itemValue;
									if (itemMethod.equals(SearchMethodEnum.Included.getMessage())){
										itemMethod = SearchMethodEnum.Like.getMessage();
									}
									if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
										itemMethod = SearchMethodEnum.NotLike.getMessage();
									}
								}
								if ("and".equalsIgnoreCase(conditionItem.getLogic())) {
									if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
										tw.eq(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
										tw.ne(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
										tw.lt(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
										tw.le(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
										tw.gt(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
										tw.ge(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
										tw.in(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
										tw.notIn(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.Like.getMessage())) {
										tw.like(itemField, value);
									} else if (itemMethod.equals(SearchMethodEnum.NotLike.getMessage())) {
										tw.notLike(itemField, value);
									}
								} else {
									if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
										tw.or(
												qw -> qw.eq(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
										tw.or(
												qw -> qw.ne(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
										tw.or(
												qw -> qw.lt(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
										tw.or(
												qw -> qw.le(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
										tw.or(
												qw -> qw.gt(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
										tw.or(
												qw -> qw.ge(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
										tw.or(
												qw -> qw.in(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
										tw.or(
												qw -> qw.notIn(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.Like.getMessage())) {
										tw.or(
												qw -> qw.like(itemField, value)
										);
									} else if (itemMethod.equals(SearchMethodEnum.NotLike.getMessage())) {
										tw.or(
												qw -> qw.notLike(itemField, value)
										);
									}
								}
							}
						}
					}
				});
			}
		}
		return queryWhere;
	}


	/**
	 * 获取条件过滤
	 *
	 * @param userInfo  用户信息
	 * @param moduleId  功能模块Id
	 * @param tableName 主表名
	 * @return
	 */
	@Override
	public String getConditionSql(UserInfo userInfo, String moduleId, String tableName,List<Object> objs) {
		StringBuilder queryWhere = new StringBuilder();
		AuthorizeVO model = this.getAuthorize(true);
		List<ResourceModel> resourceList = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
		//方案
		for (ResourceModel item : resourceList) {
			if ("jnpf_alldata".equals(item.getEnCode())) {
				StringBuilder allData = new StringBuilder();
				allData.append("alldata" );
				queryWhere = allData;
				break;
			}
			StringBuilder itemWhere = new StringBuilder();
			List<ConditionModel> conditionModelList = JsonUtil.getJsonToList(item.getConditionJson(), ConditionModel.class);
			//分组
			for (int i = 0; i < conditionModelList.size(); i++) {
				StringBuilder subWhere = new StringBuilder();
				ConditionModel conditionItem = conditionModelList.get(i);
				//条件
				for (int k = 0; k < conditionItem.getGroups().size(); k++) {
					ConditionModel.ConditionItemModel fieldItem = conditionItem.getGroups().get(k);
					if (conditionItem.getGroups().indexOf(fieldItem) > 0) {
						subWhere.append(" " + conditionItem.getLogic().toUpperCase() + " " );
					}
					String itemField = fieldItem.getField();
					if (tableName != null && !tableName.equals(fieldItem.getBindTable())) {
						continue;
					}
					if (!itemField.contains("." )) {
						itemField = fieldItem.getBindTable() + "." + itemField;
					}
					String itemValue = fieldItem.getValue();
					String itemMethod = fieldItem.getOp();
					//当前用户
					if (AuthorizeConditionEnum.USER.getCondition().equals(itemValue)) {
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
							itemValue = "%" + userInfo.getUserId() + "%";
							subWhere.append(itemField + " not Like ?");
						} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							itemValue = "%" + userInfo.getUserId() + "%";
							subWhere.append(itemField + " like ?");
						} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
							subWhere.append(itemField + " <> ?");
						} else {
							itemValue = userInfo.getUserId();
							subWhere.append(itemField + " = ?");
						}
						objs.add(itemValue);
					}
					//当前组织
					else if (AuthorizeConditionEnum.ORGANIZE.getCondition().equals(itemValue)) {
						String orgId = userInfo.getOrganizeId();
						if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
							orgId = userInfo.getDepartmentId();
						}
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
							itemValue = "%" + orgId + "%";
							subWhere.append(itemField + " not Like ?");
						} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							itemValue = "%" + orgId + "%";
							subWhere.append(itemField + " like ?");
						} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
							subWhere.append(itemField + " <> ?");
						} else {
							itemValue =  orgId;
							subWhere.append(itemField + " = ?");
						}
							objs.add(itemValue);
					}
					//当前组织及子组织
					else if (AuthorizeConditionEnum.ORGANIZEANDUNDER.getCondition().equals(itemValue)) {
						String orgId = userInfo.getOrganizeId();
						if (StringUtil.isNotEmpty(userInfo.getDepartmentId())) {
							orgId = userInfo.getDepartmentId();
						}
						//获取子组织
						List<String> underOrganizations = organizeService.getUnderOrganizations(orgId);
						underOrganizations.add(orgId);
						String organization = underOrganizations.stream()
								.map(m->"?")
								.collect(Collectors.joining("," ));
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							subWhere.append(itemField + " not in( " + organization + " )" + " " );
						} else{
							subWhere.append(itemField + " in( " + organization + " )" + " " );
						}
						objs.addAll(underOrganizations);
					}
					//当前用户及下属
					else if (AuthorizeConditionEnum.USERANDUNDER.getCondition().equals(itemValue)) {
						List<String> subOrganizeIds = new ArrayList<>();
						if (userInfo.getSubordinateIds().size() > 0) {
							subOrganizeIds = userInfo.getSubordinateIds();
						}
						subOrganizeIds.add(userInfo.getUserId());
						String ids = subOrganizeIds.stream().map(id -> "?" ).collect(Collectors.joining("," ));
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							subWhere.append(itemField + " not in( " + ids + " )" + " " );
						} else{
							subWhere.append(itemField + " in( " + ids + " )" + " " );
						}
						objs.addAll(subOrganizeIds);
					}
					//分管组织
					else if (AuthorizeConditionEnum.BRANCHMANAGEORG.getCondition().equals(itemValue)) {
						List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());
						//子
						List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);
						//父
						List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

						List<String> allIdList = new ArrayList<>();

						//子
						List<String> childList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());
						//父
						List<String> fathetList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1).map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

						for (String org : childList) {
							List<String> underOrganizations = organizeService.getUnderOrganizations(org);
							if (underOrganizations.size() > 0) {
								allIdList.addAll(underOrganizations);
							}
						}

						if (fathetList.size() > 0) {
							allIdList.addAll(fathetList);
						}
						String ids = allIdList.stream().map(id -> "?" ).collect(Collectors.joining("," ));
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							subWhere.append(itemField + " not in( " + ids + " )" + " " );
						} else{
							subWhere.append(itemField + " in( " + ids + " )" + " " );
						}
							objs.addAll(allIdList);
					}
					//分管组织及子组织
					else if (AuthorizeConditionEnum.BRANCHMANAGEORGANIZEUNDER.getCondition().equals(itemValue)) {
						List<OrganizeAdministratorEntity> organizeAdministratorEntity = organizeAdminIsTratorService.getListByUserID(userInfo.getUserId());

						List<OrganizeAdministratorEntity> organizeAdministratorEntity1 = new ArrayList<>(organizeAdministratorEntity);

						List<OrganizeAdministratorEntity> organizeAdministratorEntity2 = new ArrayList<>(organizeAdministratorEntity);

						List<String> allIdList = new ArrayList<>();
						//需要子集
						List<String> childList = new ArrayList<>();

						List<String> thisList = organizeAdministratorEntity1.stream().filter(orgAdmin -> orgAdmin.getThisLayerSelect() == 1)
								.map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

						List<String> subList = organizeAdministratorEntity2.stream().filter(orgAdmin -> orgAdmin.getSubLayerSelect() == 1)
								.map(orgAdmin -> orgAdmin.getOrganizeId()).collect(Collectors.toList());

						if (thisList.size() > 0) {
							allIdList.addAll(thisList);
							childList.addAll(thisList);
						}
						if (subList.size() > 0) {
							childList.addAll(subList);
						}

						for (String orgID : childList) {
							List<String> underOrganizations = organizeService.getUnderOrganizations(orgID);
							if (underOrganizations.size() > 0) {
								allIdList.addAll(underOrganizations);
							}
						}
						List<String> orgAndSub = allIdList.stream().distinct().collect(Collectors.toList());
						String ids = orgAndSub.stream().map(id -> "?" ).collect(Collectors.joining("," ));
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())){
							subWhere.append(itemField + " not in( " + ids + " )" + " " );
						} else{
							subWhere.append(itemField + " in( " + ids + " )" + " " );
						}
							objs.addAll(orgAndSub);
					}
					//任意文本
					else {
						if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage()) || itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							itemValue = "%" + itemValue + "%";
						}
						if (fieldItem.getType().equals(DataFieldType.Varchar.getMessage())) {
							itemValue =  itemValue;
						}
						if (itemMethod.equals(SearchMethodEnum.Equal.getMessage())) {
							subWhere.append(itemField + " = ?");
						} else if (itemMethod.equals(SearchMethodEnum.NotEqual.getMessage())) {
							subWhere.append(itemField + " <> ?");
						} else if (itemMethod.equals(SearchMethodEnum.LessThan.getMessage())) {
							subWhere.append(itemField + " < ?");
						} else if (itemMethod.equals(SearchMethodEnum.LessThanOrEqual.getMessage())) {
							subWhere.append(itemField + " <= ?");
						} else if (itemMethod.equals(SearchMethodEnum.GreaterThan.getMessage())) {
							subWhere.append(itemField + " > ?");
						} else if (itemMethod.equals(SearchMethodEnum.GreaterThanOrEqual.getMessage())) {
							subWhere.append(itemField + " >= ?");
						} else if (itemMethod.equals(SearchMethodEnum.Included.getMessage())) {
							subWhere.append(itemField + " like ?");
						} else if (itemMethod.equals(SearchMethodEnum.NotIncluded.getMessage())) {
							subWhere.append(itemField + " not Like ?");
						}
						objs.add(itemValue);
					}
				}
				if (subWhere.length() != 0) {
					itemWhere.append(" AND (" + subWhere + ")" );
				}
			}
			if (itemWhere.length() != 0) {
				queryWhere.append(itemWhere);
			}
		}
		return queryWhere.toString();
	}

	@Override
	public List<SystemBaeModel> findSystem(List<String> roleIds) {
		List<String> roleId = new ArrayList<>(roleIds.size());
		roleIds.forEach(t -> {
			roleId.add("'" + t + "'");
		});
		String join = String.join(",", roleId);
		return getBaseMapper().findSystem(join);
	}

}
